import pygame  # 游戏库
import sys  # 系统库
import traceback  #
import re
import pymysql

from PIL import ImageTk  # 图像处理库
from pygame.locals import *
import myplane  # 飞机类
import enemy  # 敌人类
import bullet  # 子弹类
import supply  # 补给类
from random import *  # 随机数类
##############
import tkinter as tk

import tkinter.messagebox
import pickle


from test_db import cursor

db = pymysql.connect(
    host="localhost",
    user="root",
    password="XingFenDe2014",
    port=3306,
    db="pythondb",
    charset="utf8"
)

pygame.init()  # 初始化pygame模块
bg_size = width, height = 1000, 700  # 游戏背景画布大小
# bg_size = width, height = 1136, 640  # 游戏背景画布大小
screen = pygame.display.set_mode(bg_size)  # 设置
pygame.display.set_caption("飞机大战---简易版v1.0")  # 设置游戏标题

background = pygame.image.load("images/background.png").convert()  # 设置游戏运行背景图
# background = pygame.image.load("images/map-blackhole.jpg").convert()  # 设置游戏运行背景图
# background = pygame.image.load("images/forest-02.jpg").convert()  # 设置游戏运行背景图
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
# 时间模块
clock = pygame.time.Clock()

# 载入游戏音乐
pygame.mixer.music.load("sound/game_music.wave")  # 游戏背景音乐
pygame.mixer.music.set_volume(0.2)  # 20%的音量

bullet_sound = pygame.mixer.Sound("sound/bullet.wav")  # 子弹声音
bullet_sound.set_volume(0.2)
bomb_sound = pygame.mixer.Sound("sound/use_bomb.wav")  # 使用炸弹声音
bomb_sound.set_volume(0.2)
supply_sound = pygame.mixer.Sound("sound/supply.wav")  # 补给声音
supply_sound.set_volume(0.2)
get_bomb_sound = pygame.mixer.Sound("sound/get_bomb.wav")  # 获得炸弹补给声音
get_bomb_sound.set_volume(0.2)
get_bullet_sound = pygame.mixer.Sound("sound/get_bullet.wav")  # 获得子弹补给声音
get_bullet_sound.set_volume(0.2)
upgrade_sound = pygame.mixer.Sound("sound/upgrade.wav")  # 更新声音
upgrade_sound.set_volume(0.2)
enemy3_fly_sound = pygame.mixer.Sound("sound/enemy3_flying.wav")  # 三级敌人飞行声音
enemy3_fly_sound.set_volume(0.2)
enemy1_down_sound = pygame.mixer.Sound("sound/enemy1_down.wav")  # 一级敌人摧毁声音
enemy1_down_sound.set_volume(0.2)
enemy2_down_sound = pygame.mixer.Sound("sound/enemy2_down.wav")  # 二级敌人摧毁声音
enemy2_down_sound.set_volume(0.2)
enemy3_down_sound = pygame.mixer.Sound("sound/enemy3_down.wav")  # 三级敌人摧毁声音
enemy3_down_sound.set_volume(0.5)
me_down_sound = pygame.mixer.Sound("sound/me_down.wav")  # 自己摧毁声音
me_down_sound.set_volume(0.2)
# menu_sound = pygame.mixer.music.load("sound/gamebg0.mp3")  # 自己摧毁声音
# pygame.mixer.music.set_volume(0.2)
# menu_sound.set_volume(0.2)
menu_sound = pygame.mixer.Sound("sound/mune.wav")  # 选择菜单时的音效
menu_sound.set_volume(0.2)
######################################################################################



# "关于"界面
def About(name):
    # 娱乐图片1 左下角
    # about_fun_img = pygame.image.load("images/about_fun.jpg")
    # about_fun_img = pygame.image.load("images/hut-min.jpg")
    # about_fun_img = pygame.image.load("images/hut.jpg")
    # about_fun_rect = about_fun_img.get_rect()
    # 娱乐图片
    about_fun2_img = pygame.image.load("images/about_fun2.png")
    # about_fun2_img = pygame.image.load("images/background.png")
    # about_fun2_img = pygame.image.load("images/hut.jpg")
    about_fun2_rect = about_fun2_img.get_rect()

    # 返回按钮
    comeback1_img = pygame.image.load("images/comeback1.png").convert_alpha()  # 返回按钮1
    comeback2_img = pygame.image.load("images/comeback2.png").convert_alpha()  # 返回按钮2
    comeback_img = comeback1_img  # 设置默认图片
    comeback_rect = comeback1_img.get_rect()  # 获取图片
    comeback_rect.left, comeback_rect.top = 1000 - 100, 700 - 100  # 设置图片显示位置

    # about_font = pygame.font.Font("font/font.TTF", 35)
    # about_font = pygame.font.SysFont("arial", 16)
    about_font = pygame.font.SysFont("simsunnsimsun", 16)
    # about_font = pygame.font.SysFont("simhei", 16)
    Author_text = about_font.render("Author:湖南工业大学 计科1902班 匡俊桦 尹文 谭岑鹏", True, WHITE)
    # Email_text = about_font.render("E-mail: kuangjunhua_cn@163.com", True, WHITE)
    # Language_text = about_font.render("Language: Python", True, WHITE)
    Bgm_text = about_font.render("Bgm: 《Into The Battlefield》", True, WHITE)
    # This book is for academic exchanges and research learning, Do not used for commercial purposes.
    # Attention1_text = about_font.render("Attention: This game is for academic exchanges ", True, WHITE)
    # Attention2_text = about_font.render("and research learning. Please do not", True, WHITE)
    # Attention3_text = about_font.render("used for commercial purposes.", True, WHITE)

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEMOTION:  # 鼠标移动
                # 返回按钮
                if comeback_rect.collidepoint(event.pos):  # 检测一个点是否包含在该 Rect 对象内 判断鼠标是否停留在该图案上 停留时高亮 否则暗淡
                    comeback_img = comeback1_img
                else:
                    comeback_img = comeback2_img

            elif event.type == MOUSEBUTTONDOWN:  # 鼠标按下
                # collidepoint(event.pos),自动检测鼠标是否停留在pos内，如果是则返回True
                if event.button == 1 and comeback_rect.collidepoint(event.pos):
                    menu_sound.play()  # 选择游戏菜单声音响应
                    Menu(name)  # 转到菜单
        # screen.blit(img,position) 设置图像以及显示的位置
        screen.blit(background, (0, 0))  # 从左上角背景图片  铺满
        screen.blit(about_fun2_img, about_fun2_rect)  # 关于的背景图片
        screen.blit(comeback_img, comeback_rect)  # 返回的图片
        screen.blit(Author_text, (10, 90))  #
        # screen.blit(Email_text, (10, 140))  #
        # screen.blit(Language_text, (10, 190))  #
        screen.blit(Bgm_text, (10, 140))  #
        # screen.blit(Attention1_text, (10, 290))
        # screen.blit(Attention2_text, (205, 340))
        # screen.blit(Attention3_text, (205, 390))
        # screen.blit(about_fun_img, (0, 700 - about_fun_rect.height))

        pygame.display.flip()  # 刷新窗口

        clock.tick(60)  # 设置图像刷新率，如果刷新率太高，图像闪的太厉害 一般设置为60帧


# 帮助界面
def Help(name):

    # 背景图片
    help_fun_img = pygame.image.load("images/about_fun2.png")  # 加载帮助的背景图片
    help_fun_rect = help_fun_img.get_rect()  # 获取图片对象
    # 返回按钮
    comeback1_img = pygame.image.load("images/comeback1.png").convert_alpha()  # 返回按钮1
    comeback2_img = pygame.image.load("images/comeback2.png").convert_alpha()  # 返回按钮2
    comeback_img = comeback1_img  # 设置默认图片 暗淡
    comeback_rect = comeback1_img.get_rect()
    comeback_rect.left, comeback_rect.top = 1000 - 100, 700 - 100
    about_font = pygame.font.SysFont("simsunnsimsun", 16)

    control1_text = about_font.render("W S A D 控制控制上下左右或者方向键控制上下左右", True, WHITE)
    control2_text = about_font.render("按空格触发导弹效果 消灭所有敌人 左下角显示导弹数量", True, WHITE)
    control3_text = about_font.render("右下角显示生命数量 并且死亡时有三秒无敌时间", True, WHITE)
    control4_text = about_font.render("每隔一段时间会出现补给 可以捡到弹药或者导弹并随玩家分数增大 难度增大", True, WHITE)
    Bgm_text = about_font.render("Bgm: 《Into The Battlefield》", True, WHITE)

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

            elif event.type == MOUSEMOTION:  # 鼠标移动
                # 返回按钮
                if comeback_rect.collidepoint(event.pos):  # 判断是否鼠标移动到返回图标上
                    comeback_img = comeback1_img  # 亮
                else:
                    comeback_img = comeback2_img  # 暗

            elif event.type == MOUSEBUTTONDOWN:  # 鼠标点击
                # collidepoint(event.pos),自动检测鼠标是否停留在pos内，如果是则返回True
                if event.button == 1 and comeback_rect.collidepoint(event.pos):
                    menu_sound.play()  # 点击声音
                    Menu(name)  # 返回菜单

        screen.blit(background, (0, 0))  # 设置背景图案
        screen.blit(help_fun_img, (0, 0))  # 设置帮助图案
        screen.blit(comeback_img, comeback_rect)  # 设置返回图案
        screen.blit(control1_text,(10, 90) )  # 关于的背景图片
        # screen.blit(comeback_img, comeback_rect)  # 返回的图片
        screen.blit(control2_text, (10, 150))  #
        screen.blit(control3_text, (10, 210))  #
        screen.blit(control4_text, (10, 260))  #
        pygame.display.flip()  # 刷新

        clock.tick(60)  # 60帧率

#排行榜界面
def scores(name):
    about_fun2_img = pygame.image.load("images/about_fun2.png")
    # about_fun2_img = pygame.image.load("images/hut.jpg")
    about_fun2_rect = about_fun2_img.get_rect()

    # 返回按钮
    comeback1_img = pygame.image.load("images/comeback1.png").convert_alpha()  # 返回按钮1
    comeback2_img = pygame.image.load("images/comeback2.png").convert_alpha()  # 返回按钮2
    comeback_img = comeback1_img  # 设置默认图片
    comeback_rect = comeback1_img.get_rect()  # 获取图片
    comeback_rect.left, comeback_rect.top = 1000 - 100, 700 - 100  # 设置图片显示位置

    cursor = db.cursor()
    sql = "select * from record_score order by score desc "
    cursor.execute(sql)
    data = cursor.fetchall()

    sql2 = "select count(*) from record_score"
    cursor.execute(sql2)
    num = cursor.fetchone()[0]

    print(num)
    # temp = re.sub(r'[\[\]\(\), ]', '', str(num))
    # # Using set
    # res = [int(i) for i in set(temp)]
    # # Result
    # num = res

    list_username= []
    list_score = []
    for row in data:
        if num:
            list_username.append(row[0])
            list_score.append(row[1])
            num-=1
        else:
            break
    db.close()

    first_name = list_username[0]
    first_score = list_score[0]
    second_name = list_username[1]
    second_score = list_score[1]
    third_name  = list_username[2]
    third_score = list_score[2]
    forth_name = list_username[3]
    forth_score = list_score[3]
    fifth_name = list_username[4]
    fifth_score = list_score[4]
    score_font = pygame.font.SysFont("simsunnsimsun", 16)
    first_text = score_font.render("第一名:"+first_name+str("  Score: %s" % first_score), True, WHITE)
    second_text = score_font.render("第二名:" + second_name +str("  Score: %s" % second_score), True, WHITE)
    third_text = score_font.render("第三名:" + third_name + str("  Score: %s" % third_score), True, WHITE)
    forth_text = score_font.render("第四名:" + forth_name + str("  Score: %s" % forth_score), True, WHITE)
    fifth_text = score_font.render("第五名:" + fifth_name + str("  Score: %s" % fifth_score), True, WHITE)

    # score_text = score_font.render(str("Score: %s" % score), True, WHITE)  # 分数
    # record_score_text = score_font.render("Best: %d User_Name:%s" % (record_score, record_name), True, WHITE)
    # Email_text = about_font.render("E-mail: kuangjunhua_cn@163.com", True, WHITE)
    # Language_text = about_font.render("Language: Python", True, WHITE)
    # Bgm_text = about_font.render("Bgm: 《Into The Battlefield》", True, WHITE)
    # This book is for academic exchanges and research learning, Do not used for commercial purposes.
    # Attention1_text = about_font.render("Attention: This game is for academic exchanges ", True, WHITE)
    # Attention2_text = about_font.render("and research learning. Please do not", True, WHITE)
    # Attention3_text = about_font.render("used for commercial purposes.", True, WHITE)

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEMOTION:  # 鼠标移动
                # 返回按钮
                if comeback_rect.collidepoint(event.pos):  # 检测一个点是否包含在该 Rect 对象内 判断鼠标是否停留在该图案上 停留时高亮 否则暗淡
                    comeback_img = comeback1_img
                else:
                    comeback_img = comeback2_img

            elif event.type == MOUSEBUTTONDOWN:  # 鼠标按下
                # collidepoint(event.pos),自动检测鼠标是否停留在pos内，如果是则返回True
                if event.button == 1 and comeback_rect.collidepoint(event.pos):
                    menu_sound.play()  # 选择游戏菜单声音响应
                    Menu(name)  # 转到菜单
        # screen.blit(img,position) 设置图像以及显示的位置
        screen.blit(background, (0, 0))  # 从左上角背景图片  铺满
        screen.blit(about_fun2_img, about_fun2_rect)  # 关于的背景图片
        screen.blit(comeback_img, comeback_rect)  # 返回的图片
        screen.blit(first_text, (10, 90))  #
        screen.blit(second_text, (10, 140))  #
        screen.blit(third_text, (10, 190))  #
        screen.blit(forth_text, (10, 240))  #
        screen.blit(fifth_text, (10, 290))  #
        # screen.blit(Bgm_text, (10, 240))  #
        # screen.blit(Attention1_text, (10, 290))
        # screen.blit(Attention2_text, (205, 340))
        # screen.blit(Attention3_text, (205, 390))
        # screen.blit(about_fun_img, (0, 700 - about_fun_rect.height))

        pygame.display.flip()  # 刷新窗口

        clock.tick(60)  # 设置图像刷新率，如果刷新率太高，图像闪的太厉害 一般设置为60帧

# 菜单界面
def Menu(name):
    # menu_sound.play()
    pygame.mixer.music.play()
    # pygame.mixer.music.fadeout(60000)
    # 娱乐图片1
    # menu_fan_img = pygame.image.load("images/menu_fun.png").convert_alpha()  # 娱乐图片
    # menu_fan_img = pygame.image.load("images/hut.jpg").convert_alpha()  # 设置菜单背景图片
    # menu_fan_img = pygame.image.load("images/systemimg.png").convert_alpha()  # 设置菜单背景图片
    menu_fan_img = pygame.image.load("images/background.png").convert_alpha()  # 娱乐图片
    menu_fan_rect = menu_fan_img.get_rect()
    menu_fan_rect.left, menu_fan_rect.top = 0, 0
    # 娱乐图片2
    # menu_fan2_img = pygame.image.load("images/menu_fun2.png").convert_alpha()  # 娱乐图片
    # menu_fan2_img = pygame.image.load("images/hut.jpg").convert_alpha()
    # menu_fan2_rect = menu_fan2_img.get_rect()
    # menu_fan2_rect.left, menu_fan2_rect.top = 1000 - menu_fan2_rect.width, 0

    # 开始游戏按钮
    begin_game1_img = pygame.image.load("images/begin_game1.png").convert_alpha()  # 开始游戏按钮
    begin_game2_img = pygame.image.load("images/begin_game2.png").convert_alpha()
    begin_game_img = begin_game1_img  # 设置默认的 开始图案
    begin_game_rect = begin_game1_img.get_rect()
    begin_game_rect.left, begin_game_rect.top = 264 + 350, 486 - 200

    # 帮助按钮
    help1_img = pygame.image.load("images/help1.png").convert_alpha()  # 帮助按钮
    help2_img = pygame.image.load("images/help2.png").convert_alpha()
    help_img = help1_img
    help_rect = help1_img.get_rect()
    help_rect.left, help_rect.top = 264 + 350, 424 + 0

    # 关于按钮
    about1_img = pygame.image.load("images/about1.png").convert_alpha()  # 关于按钮
    about2_img = pygame.image.load("images/about2.png").convert_alpha()
    about_img = about1_img
    about_rect = about1_img.get_rect()
    about_rect.left, about_rect.top = 264 + 350, 424 + 150

    # 排行榜按钮
    score1_img = pygame.image.load("images/scores.png").convert_alpha()  # 关于按钮
    # score2_img = pygame.image.load("images/about2.png").convert_alpha()
    score_img = score1_img
    score_rect = score1_img.get_rect()
    score_rect.left, about_rect.top = 264 + 350, 424 + 150

    # 鼠标解除按钮音效
    is_sound = True

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

            # 检测鼠标是否移动到暂停游戏按钮
            elif event.type == MOUSEMOTION:
                # 开始游戏按钮
                if begin_game_rect.collidepoint(event.pos):
                    begin_game_img = begin_game2_img
                else:
                    begin_game_img = begin_game1_img
                # 帮助按钮
                if help_rect.collidepoint(event.pos):
                    help_img = help1_img
                else:
                    help_img = help2_img
                # 关于按钮
                if about_rect.collidepoint(event.pos):
                    about_img = about1_img
                else:
                    about_img = about2_img
                # 排行榜按钮
                # if score_rect.collidepoint(event.pos):
                #     score_img = score1_img
                # else:
                #     about_img = about2_img

            elif event.type == MOUSEBUTTONDOWN:
                # collidepoint(event.pos),自动检测鼠标是否停留在pos内，如果是则返回True
                if event.button == 1 and about_rect.collidepoint(event.pos):
                    pygame.mixer.music.pause()
                    menu_sound.play()
                    About(name)
                elif event.button == 1 and begin_game_rect.collidepoint(event.pos):
                    pygame.mixer.music.pause()
                    menu_sound.play()
                    main(name)  # 开始游戏
                elif event.button == 1 and help_rect.collidepoint(event.pos):
                    pygame.mixer.music.pause()
                    menu_sound.play()
                    Help(name)
                elif event.button == 1 and score_rect.collidepoint(event.pos):
                    pygame.mixer.music.pause()
                    menu_sound.play()
                    scores(name)

        screen.blit(background, (0, 0))  # 背景图片
        # screen.blit(menu_fan2_img, menu_fan2_rect)
        screen.blit(menu_fan_img, (0, 0))  # 菜单背景图片
        screen.blit(begin_game_img, begin_game_rect)  # 开始游戏按钮
        screen.blit(help_img, help_rect)  # 帮助按钮
        screen.blit(about_img, about_rect)  # 关于按钮
        screen.blit(score1_img, score_rect)  # 排行榜按钮

        pygame.display.flip()  # 刷新

        clock.tick(60)  # 60帧率




#####################################################################################

def add_small_enemies(group1, group2, num):  # 添加num个一级敌人
    for i in range(num):
        e1 = enemy.SmallEnemy(bg_size)  # 初始化一级敌人
        group1.add(e1)  # 精灵1组 添加进一个一级敌人
        group2.add(e1)  # 精灵2组 添加进一个一级敌人


def add_mid_enemies(group1, group2, num):  # 与上同理 添加num个二级敌人
    for i in range(num):
        e1 = enemy.MidEnemy(bg_size)
        group1.add(e1)
        group2.add(e1)


def add_big_enemies(group1, group2, num):  # 与上同理 添加num个三级敌人
    for i in range(num):
        e1 = enemy.BigEnemy(bg_size)
        group1.add(e1)
        group2.add(e1)

def add_boss0(group1, group2, num):  # 与上同理 添加num个三级敌人
    for i in range(num):
        e1 = enemy.boss0(bg_size)
        group1.add(e1)
        group2.add(e1)

def add_boss1(group1, group2, num):  # 与上同理 添加num个三级敌人
    for i in range(num):
        e1 = enemy.boss1(bg_size)
        group1.add(e1)
        group2.add(e1)

def add_boss2(group1, group2, num):  # 与上同理 添加num个三级敌人
    for i in range(num):
        e1 = enemy.boss2(bg_size)
        group1.add(e1)
        group2.add(e1)

def add_boss3(group1, group2, num):  # 与上同理 添加num个三级敌人
    for i in range(num):
        e1 = enemy.boss3(bg_size)
        group1.add(e1)
        group2.add(e1)

def add_boss4(group1, group2, num):  # 与上同理 添加num个三级敌人
    for i in range(num):
        e1 = enemy.boss4(bg_size)
        group1.add(e1)
        group2.add(e1)

def add_boss5(group1, group2, num):  # 与上同理 添加num个三级敌人
    for i in range(num):
        e1 = enemy.boss5(bg_size)
        group1.add(e1)
        group2.add(e1)
def inc_speed(target, inc):  # 速度增加inc
    for each in target:
        each.speed += inc


def main(name):
    pygame.mixer.music.play(-1)

    clock = pygame.time.Clock()  # 获取时钟对象

    # 中弹图片索引
    e1_destroy_index = 0  # 敌人被摧毁索引
    e2_destroy_index = 0  # 敌人被摧毁索引
    e3_destroy_index = 0  # 敌人被摧毁索引
    e4_destroy_index = 0  # 敌人被摧毁索引
    e5_destroy_index = 0  # 敌人被摧毁索引
    e6_destroy_index = 0  # 敌人被摧毁索引
    e7_destroy_index = 0  # 敌人被摧毁索引
    e8_destroy_index = 0  # 敌人被摧毁索引
    e9_destroy_index = 0  # 敌人被摧毁索引
    me_destroy_index = 0  # 自己被摧毁索引

    me = myplane.MyPlane(bg_size)  # 实例化我的飞机

    enemies = pygame.sprite.Group()  # 敌人 精灵组

    # 生成敌方小型飞机
    small_enemies = pygame.sprite.Group()  # 一级敌人精灵组
    add_small_enemies(small_enemies, enemies, 15)  # 添加15个一级敌人

    mid_enemies = pygame.sprite.Group()  # 二级敌人精灵组
    add_mid_enemies(mid_enemies, enemies, 5)  # 添加5个二级敌人

    big_enemies = pygame.sprite.Group()  # 三级敌人精灵组
    add_big_enemies(big_enemies, enemies, 1)  # 添加1个三级敌人

    boss0 = pygame.sprite.Group()
    add_boss0(boss0,enemies,1)

    boss1 = pygame.sprite.Group()
    add_boss1(boss1, enemies, 1)

    boss2 = pygame.sprite.Group()
    add_boss2(boss2, enemies, 1)

    boss3 = pygame.sprite.Group()
    add_boss3(boss3, enemies, 1)

    boss4 = pygame.sprite.Group()
    add_boss4(boss4, enemies, 1)

    boss5 = pygame.sprite.Group()
    add_boss5(boss5, enemies, 1)

    running = True  # 是否运行
    switch_image = True  #
    delay = 100  # 延迟时间
    score = 0  # 得分
    once_score = 0 # 单次得分
    score_font = pygame.font.Font("font/font.ttf", 36)  # 设置得分字体

    bullets = []  # 子弹

    # 生成普通子弹
    bullet1 = []
    bullet1_index = 0
    BULLET1_NUM = 4
    for i in range(BULLET1_NUM):
        bullet1.append(bullet.Bullet1(me.rect.midtop))  # 添加3个一级弹药补给

    # 生命数量
    # life_image = pygame.image.load("images/life.png").convert_alpha()
    # life_image = pygame.image.load("images/whitePlane.png").convert_alpha()
    life_image = pygame.image.load("images/red.png").convert_alpha()
    life_rect = life_image.get_rect()
    life_num = 3  # 默认3条命

    # 游戏结束画面
    gameover_font = pygame.font.Font("font/font.ttf", 48)  # 游戏结束字体
    again_image = pygame.image.load("images/again.png").convert_alpha()  # 再来一次图案
    again_rect = again_image.get_rect()
    gameover_image = pygame.image.load("images/gameover.png").convert_alpha()  # 退出游戏
    gameover_rect = gameover_image.get_rect()

    # DOUBLE_BULLET_TIME = USEREVENT + 1  # 双倍子弹时间为24+1 即25
    DOUBLE_BULLET_TIME = 25 # 双倍子弹时间为24+1 即25
    THREE_BULLET_TIME =  25
    # 解除我方飞机无敌状态
    # INVINCEBLE_TIME = USEREVENT + 2  # 无敌时间为24+2 26
    INVINCEBLE_TIME = 26  # 无敌时间为24+2 26
    # 生成超级子弹
    bullet2 = []
    bullet2_index = 0
    BULLET2_NUM = 8
    for i in range(BULLET2_NUM // 2):  # 添加3个二级子弹补给
        bullet2.append(bullet.Bullet2((me.rect.centerx - 33, me.rect.centery)))  # 添加的生成位置1
        bullet2.append(bullet.Bullet2((me.rect.centerx + 30, me.rect.centery)))  # 添加的生成位置2

    # 生成超级子弹
    bullet3 = []
    bullet3_index = 0
    BULLET3_NUM = 16
    for i in range(BULLET3_NUM // 4):  # 添加3个三级子弹补给
        bullet3.append(bullet.Bullet3((me.rect.centerx - 33, me.rect.centery)))  # 添加的生成位置1
        bullet3.append(bullet.Bullet3((me.rect.centerx + 30, me.rect.centery)))  # 添加的生成位置2
        bullet3.append(bullet.Bullet3((me.rect.centerx - 50, me.rect.centery)))  # 添加的生成位置1
        bullet3.append(bullet.Bullet3((me.rect.centerx + 50, me.rect.centery)))  # 添加的生成位置2

    # 标记是否使用超级子弹
    is_double_bullet = False  # 默认否认
    is_three_bullet = False  # 默认否认

    level = 1 #默认等级

    # 全屏炸弹
    # bomb_image = pygame.image.load("images/bomb.png").convert_alpha()
    bomb_image = pygame.image.load("images/bomb1.png").convert_alpha()
    bomb_rect = bomb_image.get_rect()
    bomb_font = pygame.font.Font("font/font.ttf", 48)
    bomb_num = 3  # 默认3个

    # 每30秒发放一个补给包
    bullet_supply = supply.Bullet_Supply(bg_size)
    bullet_supply1 = supply.Bullet_Supply1(bg_size)
    # bullet_supply2 = supply.Bullet_Supply2(bg_size)
    bomb_supply = supply.Bomb_Supply(bg_size)
    # life_supply = supply.Life_Supply(bg_size)
    # SUPPLY_TIME = USEREVENT
    SUPPLY_TIME = 24
    pygame.time.set_timer(SUPPLY_TIME, 10 * 1000)  # 3000 *10 ms

    # 阻止重复读取成绩记录文件
    recorded = False  # 记录 浮标

    # 标志是否暂停游戏
    paused = False  # 暂停 浮标
    #######################
    stopping_img = pygame.image.load("images/stopping.png").convert_alpha()  # 暂停提示图片
    stopping_rect = stopping_img.get_rect()
    stopping_rect.left, stopping_rect.top = width / 2 - stopping_rect.width / 2, \
                                            height / 2 - stopping_rect.height / 2  # 暂停显示的位置
    # stopping_rect.left, stopping_rect.top = 200,300  # 暂停显示的位置
    #########################
    paused_nor_image = pygame.image.load("images/pause_nor.png").convert_alpha()  # 暂停图标1
    pause_pressed_image = pygame.image.load("images/pause_pressed.png").convert_alpha()  # 暂停图标2
    resume_nor_image = pygame.image.load("images/resume_nor.png").convert_alpha()  # 恢复图标1
    resume_pressed_image = pygame.image.load("images/resume_pressed.png").convert_alpha()  # 恢复图标2
    paused_rect = paused_nor_image.get_rect()
    paused_rect.left, paused_rect.top = width - paused_rect.width - 10, 10  # 设置暂停图标位置
    paused_image = paused_nor_image
    # screen.blit(stopping_img, stopping_rect)  # 背景图片加载
    while running:  # 当运行时
        screen.blit(background, (0, 0))  # 背景图片加载
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEBUTTONDOWN:  # 鼠标点击
                if event.button == 1 and paused_rect.collidepoint(event.pos):  # 鼠标左键点击
                    # screen.blit(stopping_img, stopping_rect)  # 背景图片加载
                    paused = not paused  # 取反
                    if paused:  # 当点击暂停
                        # screen.blit(stopping_img, stopping_rect)  # 背景图片加载
                        # pygame.time.wait(3000)
                        pygame.time.set_timer(SUPPLY_TIME, 0)  # 暂停补给
                        pygame.mixer.music.pause()  # 背景音乐暂停
                        pygame.mixer.pause()  # 模块暂停
                        paused_image = resume_pressed_image  # 将暂停按钮图标换成恢复按钮图标

                        # screen.blit(stopping_img, stopping_rect)  # 背景图片加载
                        # pygame.display.update()
                        # screen.blit(stopping_img, (200, 300))  # 背景图片加载
                    else:  # 否则点击继续
                        pygame.time.set_timer(SUPPLY_TIME, 20 * 1000)  # 继续30s生成一次补给
                        pygame.mixer.music.unpause()  # 背景音乐恢复
                        pygame.mixer.unpause()  # 模块恢复
                        paused_image = pause_pressed_image  # 按钮换成暂停图标
                        # pygame.display.update()
            elif event.type == MOUSEMOTION:  # 鼠标移动
                if paused_rect.collidepoint(event.pos):  # 移动到暂停按钮上
                    if paused:  # 当是暂停状态时
                        paused_image = resume_pressed_image  # 为恢复按钮的按下状态
                    else:  # 当运行状态下
                        paused_image = pause_pressed_image  # 否则为暂停按钮的按下状态
                else:  # 鼠标在按钮之外
                    if paused:  # 暂停模式下
                        paused_image = resume_nor_image  # 为恢复按钮的待机状态
                    else:  # 运行状态下
                        paused_image = paused_nor_image  # 为暂停按钮的待机状态
            elif event.type == KEYDOWN:  # 否则为键盘输入时
                if event.key == K_SPACE:  # 空格键 即全屏轰炸 清屏
                    if bomb_num:  # 如果还有炸弹
                        bomb_num -= 1  # 炸弹减少1
                        bomb_sound.play()  # 炸弹声音
                        for each in enemies:  # 对于每一个敌人 精灵组
                            if each.rect.bottom > 0:  # 如果在边界之内
                                each.active = False  # 灭活
            elif event.type == SUPPLY_TIME:  # 为一级子弹补给时刻
                supply_sound.play()  # 补给获取声音
                if choice([True, False]):
                    bomb_supply.reset()  # 重置炸弹补给
                    # life_supply.reset() #重置生命补给
                else:
                    bullet_supply.reset()  # 重置子弹补给
                    bullet_supply1.reset()  # 重置子弹补给

            elif event.type == DOUBLE_BULLET_TIME:  # 为二级子弹补给时刻
                is_double_bullet = False  #
                # is_three_bullet = False  # 默认否认
                pygame.time.set_timer(DOUBLE_BULLET_TIME, 0)  # 设置二级子弹状态存在时间
            elif event.type == THREE_BULLET_TIME:  # 为二级子弹补给时刻
                # is_double_bullet = False  #
                is_three_bullet = False  # 默认否认
                pygame.time.set_timer(THREE_BULLET_TIME, 0)  # 设置二级子弹状态存在时间
            elif event.type == INVINCEBLE_TIME:  # 为无敌时刻
                me.invincible = False
                pygame.time.set_timer(INVINCEBLE_TIME, 0)  # 无敌时间

        # 根据用户的得分增加难度
        if level == 1 and score > 10000:
            level = 2  # 升级
            upgrade_sound.play()  # 升级声音
            add_small_enemies(small_enemies, enemies, 3)  # 多添加3个一级敌人
            add_mid_enemies(mid_enemies, enemies, 2)  # 多添加2个二级敌人
            add_big_enemies(big_enemies, enemies, 1)  # 多添加1个三级敌人
            inc_speed(small_enemies, 1)  # 增加一级敌人移动速度
        elif level == 2 and score > 20000:
            level = 3  # 升级
            upgrade_sound.play()  # 升级声音

            add_small_enemies(small_enemies, enemies, 5)  # 多添加5个一级敌人
            add_mid_enemies(mid_enemies, enemies, 3)  # 多添加3个二级敌人
            add_big_enemies(big_enemies, enemies, 2)  # 多添加2个三级敌人
            add_boss0(boss0,enemies,1)
            # inc_speed(small_enemies, 1)  # 增加一级敌人移动速度
            inc_speed(mid_enemies, 1)  # 增加二级敌人移动速度
        elif level == 3 and score > 30000:
            level = 4  # 升级
            upgrade_sound.play()  # 升级声音
            add_small_enemies(small_enemies, enemies, 5)  # 多添加5个一级敌人
            add_mid_enemies(mid_enemies, enemies, 3)  # 多添加3个二级敌人
            add_big_enemies(big_enemies, enemies, 2)  # 多添加2个三级敌人
            add_boss0(boss1, enemies, 1)
            # inc_speed(small_enemies, 1)  # 增加一级敌人移动速度
            # inc_speed(mid_enemies, 1)  # 增加二级敌人移动速度
            inc_speed(big_enemies, 1)  # 增加三级敌人移动速度
        elif level == 4 and score > 50000:
            level = 5  # 升级
            upgrade_sound.play()  # 升级声音
            add_small_enemies(small_enemies, enemies, 5)  # 多添加5个一级敌人
            add_mid_enemies(mid_enemies, enemies, 3)  # 多添加3个二级敌人
            add_big_enemies(big_enemies, enemies, 2)  # 多添加3个二级敌人
            add_boss0(boss2, enemies, 1)
            # inc_speed(small_enemies, 1)  # 增加一级敌人移动速度
            # inc_speed(mid_enemies, 1)  # 增加二级敌人移动速度
            # inc_speed(big_enemies, 1)  # 增加三级敌人移动速度
            inc_speed(boss2,1)
        elif level == 5 and score > 70000:
            level = 6  # 升级
            upgrade_sound.play()  # 升级声音
            add_small_enemies(small_enemies, enemies, 5)  # 多添加5个一级敌人
            add_mid_enemies(mid_enemies, enemies, 3)  # 多添加3个二级敌人
            add_big_enemies(big_enemies, enemies, 2)  # 多添加3个二级敌人
            add_boss0(boss3, enemies, 1)
            # inc_speed(small_enemies, 1)  # 增加一级敌人移动速度
            # inc_speed(mid_enemies, 1)  # 增加二级敌人移动速度
            # inc_speed(big_enemies, 1)  # 增加三级敌人移动速度
            inc_speed(boss3,1)
        elif level == 6 and score > 90000:
            level = 7  # 升级
            upgrade_sound.play()  # 升级声音
            add_small_enemies(small_enemies, enemies, 5)  # 多添加5个一级敌人
            add_mid_enemies(mid_enemies, enemies, 3)  # 多添加3个二级敌人
            add_big_enemies(big_enemies, enemies, 2)  # 多添加3个二级敌人
            add_boss0(boss4, enemies, 1)
            # inc_speed(small_enemies, 1)  # 增加一级敌人移动速度
            # inc_speed(mid_enemies, 1)  # 增加二级敌人移动速度
            # inc_speed(big_enemies, 1)  # 增加三级敌人移动速度
            # inc_speed(boss3)
        elif level == 7 and score > 110000:
            level = 8  # 升级
            upgrade_sound.play()  # 升级声音
            add_small_enemies(small_enemies, enemies, 5)  # 多添加5个一级敌人
            add_mid_enemies(mid_enemies, enemies, 3)  # 多添加3个二级敌人
            add_big_enemies(big_enemies, enemies, 2)  # 多添加3个二级敌人
            add_boss0(boss5, enemies, 1)
            # inc_speed(small_enemies, 1)  # 增加一级敌人移动速度
            # inc_speed(mid_enemies, 1)  # 增加二级敌人移动速度
            # inc_speed(big_enemies, 1)  # 增加三级敌人移动速度
            # inc_speed(boss3)
        # screen.blit(background, (0, 0))  # 背景图片加载
        # pygame.display.update()

        if(200000>once_score>=100000):
            is_double_bullet = True
        elif(once_score>=500000):
            is_double_bullet = False
            is_three_bullet = True
        elif(once_score==0):
            is_double_bullet = False
            is_three_bullet = False

        if life_num and not paused:  # 如果还有生命 并且没有暂停
            # 绘制全屏炸弹补给并检测是否获得
            if bomb_supply.active:
                bomb_supply.move()
                screen.blit(bomb_supply.image, bomb_supply.rect)  # 生成炸弹补给位置
                if pygame.sprite.collide_mask(bomb_supply, me):  # 当捡到时
                    get_bomb_sound.play()  # 捡到补给声音
                    if bomb_num < 3:  # 当炸弹没满时
                        bomb_num += 1
                    bomb_supply.active = False

            # if life_supply.active:
            #     life_supply.move()
            #     screen.blit(life_supply.image, life_supply.rect)  # 生成生命补给位置
            #     if pygame.sprite.collide_mask(life_supply, me):  # 当捡到时
            #         get_bomb_sound.play()  # 捡到补给声音
            #         if bomb_num < 3:  # 当生命没满时
            #             bomb_num += 1
            #         life_supply.active = False

            # 发射子弹 ???
            if not (delay % 10):  # 当delay是10的倍数时
                bullet_sound.play()  # 子弹发射声音
                if is_double_bullet:  # 二级子弹
                    bullets = bullet2
                    bullets[bullet2_index].reset((me.rect.centerx - 33, me.rect.centery))
                    bullets[bullet2_index + 1].reset((me.rect.centerx + 33, me.rect.centery))
                    bullet2_index = (bullet2_index + 2) % BULLET2_NUM

                elif is_three_bullet:  # 三级子弹
                    bullets = bullet3
                    bullets[bullet3_index].reset((me.rect.centerx - 33, me.rect.centery))
                    bullets[bullet3_index + 1].reset((me.rect.centerx + 33, me.rect.centery))
                    bullets[bullet3_index + 2].reset((me.rect.centerx - 50, me.rect.centery))
                    bullets[bullet3_index + 3].reset((me.rect.centerx + 50, me.rect.centery))
                    bullet3_index = (bullet3_index + 4) % BULLET3_NUM

                else:  # 一级子弹
                    bullets = bullet1
                    # bullets[bullet1_index].reset(me.rect.midtop)
                    bullets[bullet1_index].reset((me.rect.centerx -8, me.rect.centery))
                    bullet1_index = (bullet1_index + 1) % BULLET1_NUM
            # 检测子弹是否击中敌机
            for b in bullets:
                if b.active:  # 子弹激活
                    b.move()  # 子弹移动
                    screen.blit(b.image, b.rect)  # 子弹生成
                    enemy_hit = pygame.sprite.spritecollide(b, enemies, False, pygame.sprite.collide_mask)  # 判断是否击中
                    if enemy_hit:  # 击中
                        b.active = False  # 子弹失活
                        for e in enemy_hit:  # 每个击中
                            if e in mid_enemies or e in big_enemies or e in boss0 or e in boss1 or e in boss2 or e in boss3 or e in boss4 or e in boss5:  # 击中二级或三级敌人 一次打不死 扣血
                                e.hit = True  # 击中
                                e.energy -= 1  # 扣一滴血
                                if e.energy == 0:  # 当没血时
                                    e.active = False  # 敌人消失 失活
                            else:  # 否则打中一级敌人时
                                e.active = False  # 直接打死 失活

            # 绘制全屏炸弹补给并检测是否获得 ????
            if bullet_supply.active:  # 获得了炸弹补给
                bullet_supply.move()  # 移动炸弹补给
                screen.blit(bullet_supply.image, bullet_supply.rect)  #
                if pygame.sprite.collide_mask(bullet_supply, me):  # 检测是否捡到
                    get_bullet_sound.play()  # 捡到音效
                    is_double_bullet = True
                    pygame.time.set_timer(DOUBLE_BULLET_TIME, 10 * 1000)  # 18s之后第二个补给？
                    bullet_supply.active = False

            if bullet_supply1.active:  # 获得了炸弹补给
                bullet_supply1.move()  # 移动炸弹补给
                screen.blit(bullet_supply1.image, bullet_supply1.rect)  #
                if pygame.sprite.collide_mask(bullet_supply1, me):  # 检测是否捡到
                    get_bullet_sound.play()  # 捡到音效
                    is_three_bullet = True
                    pygame.time.set_timer(DOUBLE_BULLET_TIME, 10 * 1000)  # 18s之后第二个补给？
                    bullet_supply1.active = False



            # 绘制大型敌机
            for each in boss0:  # 三级敌人
                if each.active:  # 存活
                    each.move()
                    if each.hit:  # 被击中
                        # screen.blit(each.image_hit, each.rect)
                        each.hit = False
                    else:
                        screen.blit(each.image1, each.rect)

                    if each.rect.bottom == -50:  # ？？？
                        enemy3_fly_sound.play(-1)

                    # 绘制血槽pygame.draw.line(位置，颜色，起始点，终止点，宽度)
                    pygame.draw.line(screen, BLACK, \
                                     (each.rect.left, each.rect.top - 5), \
                                     (each.rect.right, each.rect.top - 5), \
                                     2)  # 画一条直线 默认黑色的血

                    energy_remain = each.energy / enemy.boss0.energy  # 血量剩余
                    if energy_remain > 0.2:  # 大于20%血量
                        energy_color = GREEN  # 绿色
                    else:  # 否则
                        energy_color = RED  # 红色
                    pygame.draw.line(screen, energy_color, \
                                     (each.rect.left, each.rect.top - 5), \
                                     (each.rect.left + each.rect.width * energy_remain, \
                                      each.rect.top - 5), \
                                     2)

                else:  # 不存活
                    if not (delay % 3):  # 是3的倍数
                        if e4_destroy_index == 0:  # 3级敌人死亡
                            enemy3_down_sound.play()  # 死亡音效
                        screen.blit(each.destroy_images[e4_destroy_index], each.rect)
                        e4_destroy_index = (e4_destroy_index + 1) % 6
                        if e4_destroy_index == 0:
                            me_down_sound.stop()
                            score += 10000  # 加10000分
                            once_score += 10000
                            each.reset()  # 重置该精灵
            # 绘制大型敌机
            for each in boss1:  # 三级敌人
                if each.active:  # 存活
                    each.move()
                    if each.hit:  # 被击中
                        # screen.blit(each.image_hit, each.rect)
                        each.hit = False
                    else:
                        screen.blit(each.image1, each.rect)

                    if each.rect.bottom == -50:  # ？？？
                        enemy3_fly_sound.play(-1)

                    # 绘制血槽pygame.draw.line(位置，颜色，起始点，终止点，宽度)
                    pygame.draw.line(screen, BLACK, \
                                     (each.rect.left, each.rect.top - 5), \
                                     (each.rect.right, each.rect.top - 5), \
                                     2)  # 画一条直线 默认黑色的血

                    energy_remain = each.energy / enemy.boss1.energy  # 血量剩余
                    if energy_remain > 0.2:  # 大于20%血量
                        energy_color = GREEN  # 绿色
                    else:  # 否则
                        energy_color = RED  # 红色
                    pygame.draw.line(screen, energy_color, \
                                     (each.rect.left, each.rect.top - 5), \
                                     (each.rect.left + each.rect.width * energy_remain, \
                                      each.rect.top - 5), \
                                     2)

                else:  # 不存活
                    if not (delay % 3):  # 是3的倍数
                        if e5_destroy_index == 0:  # 3级敌人死亡
                            enemy3_down_sound.play()  # 死亡音效
                        screen.blit(each.destroy_images[e5_destroy_index], each.rect)
                        e5_destroy_index = (e5_destroy_index + 1) % 6
                        if e5_destroy_index == 0:
                            me_down_sound.stop()
                            score += 10000  # 加10000分
                            once_score += 10000
                            each.reset()  # 重置该精灵

            # 绘制大型敌机
            for each in boss2:  # 三级敌人
                if each.active:  # 存活
                    each.move()
                    if each.hit:  # 被击中
                        # screen.blit(each.image_hit, each.rect)
                        each.hit = False
                    else:
                        screen.blit(each.image1, each.rect)

                    if each.rect.bottom == -50:  # ？？？
                        enemy3_fly_sound.play(-1)

                    # 绘制血槽pygame.draw.line(位置，颜色，起始点，终止点，宽度)
                    pygame.draw.line(screen, BLACK, \
                                     (each.rect.left, each.rect.top - 5), \
                                     (each.rect.right, each.rect.top - 5), \
                                     2)  # 画一条直线 默认黑色的血

                    energy_remain = each.energy / enemy.boss2.energy  # 血量剩余
                    if energy_remain > 0.2:  # 大于20%血量
                        energy_color = GREEN  # 绿色
                    else:  # 否则
                        energy_color = RED  # 红色
                    pygame.draw.line(screen, energy_color, \
                                     (each.rect.left, each.rect.top - 5), \
                                     (each.rect.left + each.rect.width * energy_remain, \
                                      each.rect.top - 5), \
                                     2)

                else:  # 不存活
                    if not (delay % 3):  # 是3的倍数
                        if e6_destroy_index == 0:  # 3级敌人死亡
                            enemy3_down_sound.play()  # 死亡音效
                        screen.blit(each.destroy_images[e6_destroy_index], each.rect)
                        e6_destroy_index = (e6_destroy_index + 1) % 6
                        if e6_destroy_index == 0:
                            me_down_sound.stop()
                            score += 10000  # 加10000分
                            once_score += 10000
                            each.reset()  # 重置该精灵

            # 绘制大型敌机
            for each in boss3:  # 三级敌人
                if each.active:  # 存活
                    each.move()
                    if each.hit:  # 被击中
                        # screen.blit(each.image_hit, each.rect)
                        each.hit = False
                    else:
                        screen.blit(each.image1, each.rect)

                    if each.rect.bottom == -50:  # ？？？
                        enemy3_fly_sound.play(-1)

                    # 绘制血槽pygame.draw.line(位置，颜色，起始点，终止点，宽度)
                    pygame.draw.line(screen, BLACK, \
                                     (each.rect.left, each.rect.top - 5), \
                                     (each.rect.right, each.rect.top - 5), \
                                     2)  # 画一条直线 默认黑色的血

                    energy_remain = each.energy / enemy.boss3.energy  # 血量剩余
                    if energy_remain > 0.2:  # 大于20%血量
                        energy_color = GREEN  # 绿色
                    else:  # 否则
                        energy_color = RED  # 红色
                    pygame.draw.line(screen, energy_color, \
                                     (each.rect.left, each.rect.top - 5), \
                                     (each.rect.left + each.rect.width * energy_remain, \
                                      each.rect.top - 5), \
                                     2)

                else:  # 不存活
                    if not (delay % 3):  # 是3的倍数
                        if e7_destroy_index == 0:  # 3级敌人死亡
                            enemy3_down_sound.play()  # 死亡音效
                        screen.blit(each.destroy_images[e7_destroy_index], each.rect)
                        e7_destroy_index = (e7_destroy_index + 1) % 6
                        if e7_destroy_index == 0:
                            me_down_sound.stop()
                            score += 10000  # 加10000分
                            once_score += 10000
                            each.reset()  # 重置该精灵

            # 绘制大型敌机
            for each in boss4:  # 三级敌人
                if each.active:  # 存活
                    each.move()
                    if each.hit:  # 被击中
                        # screen.blit(each.image_hit, each.rect)
                        each.hit = False
                    else:
                        screen.blit(each.image1, each.rect)

                    if each.rect.bottom == -50:  # ？？？
                        enemy3_fly_sound.play(-1)

                    # 绘制血槽pygame.draw.line(位置，颜色，起始点，终止点，宽度)
                    pygame.draw.line(screen, BLACK, \
                                     (each.rect.left, each.rect.top - 5), \
                                     (each.rect.right, each.rect.top - 5), \
                                     2)  # 画一条直线 默认黑色的血

                    energy_remain = each.energy / enemy.boss4.energy  # 血量剩余
                    if energy_remain > 0.2:  # 大于20%血量
                        energy_color = GREEN  # 绿色
                    else:  # 否则
                        energy_color = RED  # 红色
                    pygame.draw.line(screen, energy_color, \
                                     (each.rect.left, each.rect.top - 5), \
                                     (each.rect.left + each.rect.width * energy_remain, \
                                      each.rect.top - 5), \
                                     2)

                else:  # 不存活
                    if not (delay % 3):  # 是3的倍数
                        if e8_destroy_index == 0:  # 3级敌人死亡
                            enemy3_down_sound.play()  # 死亡音效
                        screen.blit(each.destroy_images[e8_destroy_index], each.rect)
                        e8_destroy_index = (e8_destroy_index + 1) % 6
                        if e8_destroy_index == 0:
                            me_down_sound.stop()
                            score += 10000  # 加10000分
                            once_score += 10000
                            each.reset()  # 重置该精灵

            # 绘制大型敌机
            for each in boss5:  # 三级敌人
                if each.active:  # 存活
                    each.move()
                    if each.hit:  # 被击中
                        # screen.blit(each.image_hit, each.rect)
                        each.hit = False
                    else:
                        screen.blit(each.image1, each.rect)

                    if each.rect.bottom == -50:  # ？？？
                        enemy3_fly_sound.play(-1)

                    # 绘制血槽pygame.draw.line(位置，颜色，起始点，终止点，宽度)
                    pygame.draw.line(screen, BLACK, \
                                     (each.rect.left, each.rect.top - 5), \
                                     (each.rect.right, each.rect.top - 5), \
                                     2)  # 画一条直线 默认黑色的血

                    energy_remain = each.energy / enemy.boss5.energy  # 血量剩余
                    if energy_remain > 0.2:  # 大于20%血量
                        energy_color = GREEN  # 绿色
                    else:  # 否则
                        energy_color = RED  # 红色
                    pygame.draw.line(screen, energy_color, \
                                     (each.rect.left, each.rect.top - 5), \
                                     (each.rect.left + each.rect.width * energy_remain, \
                                      each.rect.top - 5), \
                                     2)

                else:  # 不存活
                    if not (delay % 3):  # 是3的倍数
                        if e9_destroy_index == 0:  # 3级敌人死亡
                            enemy3_down_sound.play()  # 死亡音效
                        screen.blit(each.destroy_images[e9_destroy_index], each.rect)
                        e9_destroy_index = (e9_destroy_index + 1) % 6
                        if e9_destroy_index == 0:
                            me_down_sound.stop()
                            score += 10000  # 加10000分
                            once_score +=10000
                            each.reset()  # 重置该精灵

            # 绘制大型敌机
            for each in big_enemies:  # 三级敌人
                if each.active:  # 存活
                    each.move()
                    if each.hit:  # 被击中
                        # screen.blit(each.image_hit, each.rect)
                        each.hit = False
                    else:
                        if switch_image:
                            screen.blit(each.image1, each.rect)
                        else:
                            screen.blit(each.image2, each.rect)
                    if each.rect.bottom == -50:  # ？？？
                        enemy3_fly_sound.play(-1)

                    # 绘制血槽pygame.draw.line(位置，颜色，起始点，终止点，宽度)
                    pygame.draw.line(screen, BLACK, \
                                     (each.rect.left, each.rect.top - 5), \
                                     (each.rect.right, each.rect.top - 5), \
                                     2)  # 画一条直线 默认黑色的血

                    energy_remain = each.energy / enemy.BigEnemy.energy  # 血量剩余
                    if energy_remain > 0.2:  # 大于20%血量
                        energy_color = GREEN  # 绿色
                    else:  # 否则
                        energy_color = RED  # 红色
                    pygame.draw.line(screen, energy_color, \
                                     (each.rect.left, each.rect.top - 5), \
                                     (each.rect.left + each.rect.width * energy_remain, \
                                      each.rect.top - 5), \
                                     2)

                else:  # 不存活
                    if not (delay % 3):  # 是3的倍数
                        if e3_destroy_index == 0:  # 3级敌人死亡
                            enemy3_down_sound.play()  # 死亡音效
                        screen.blit(each.destroy_images[e3_destroy_index], each.rect)
                        e3_destroy_index = (e3_destroy_index + 1) % 6
                        if e3_destroy_index == 0:
                            me_down_sound.stop()
                            score += 10000  # 加10000分
                            once_score += 10000
                            each.reset()  # 重置该精灵

            # 绘制中型敌机
            for each in mid_enemies:  # 二级敌人 同上
                if each.active:
                    each.move()

                    if each.hit:
                        # screen.blit(each.image_hit, each.rect)
                        each.hit = False
                    else:
                        screen.blit(each.image1, each.rect)

                    # 绘制血槽
                    pygame.draw.line(screen, BLACK, \
                                     (each.rect.left, each.rect.top - 5), \
                                     (each.rect.right, each.rect.top - 5), \
                                     2)

                    energy_remain = each.energy / enemy.MidEnemy.energy
                    if energy_remain > 0.2:
                        energy_color = GREEN
                    else:
                        energy_color = RED
                    pygame.draw.line(screen, energy_color, \
                                     (each.rect.left, each.rect.top - 5), \
                                     (each.rect.left + each.rect.width * energy_remain, \
                                      each.rect.top - 5), \
                                     2)
                else:
                    if not (delay % 3):
                        if e2_destroy_index == 0:
                            enemy2_down_sound.play()
                        screen.blit(each.destroy_images[e2_destroy_index], each.rect)
                        e2_destroy_index = (e2_destroy_index + 1) % 4
                        if e2_destroy_index == 0:
                            score += 5000  # 加5000分
                            once_score += 5000
                            each.reset()

            # 绘制小型敌机
            for each in small_enemies:  # 一级敌人 一次击中就死 没有血条
                if each.active:
                    each.move()
                    screen.blit(each.image1, each.rect)
                else:
                    if not (delay % 3):
                        if e1_destroy_index == 0:
                            enemy1_down_sound.play()
                        screen.blit(each.destroy_images[e1_destroy_index], each.rect)
                        e1_destroy_index = (e1_destroy_index + 1) % 4
                        if e1_destroy_index == 0:
                            score += 1000
                            once_score += 1000
                            each.reset()

            key_pressed = pygame.key.get_pressed()  # 获得键盘输入
            if key_pressed[K_w] or key_pressed[K_UP]:  # 键盘输入w或者向上
                me.moveUp()  # 向上移动
            if key_pressed[K_s] or key_pressed[K_DOWN]:  # 键盘输入s或者向下
                me.moveDown()  # 向下移动
            if key_pressed[K_a] or key_pressed[K_LEFT]:  # 键盘输入a或者向左
                me.moveLeft()  # 向左移动
            if key_pressed[K_d] or key_pressed[K_RIGHT]:  # 键盘输入d或者向右
                me.moveRight()  # 向右移动

            # 检测我方飞机是否被撞
            enemies_down = pygame.sprite.spritecollide(me, enemies, False, pygame.sprite.collide_mask)
            if enemies_down and not me.invincible:  # 如果敌人死亡并且自己不是无敌
                me.active = False  # 自己死亡
                once_score = 0 # 分数清零
                for e in enemies_down:  # 与碰撞的敌机一起死亡
                    e.active = False

            # 绘制我方飞机
            if me.active:
                if switch_image:
                    screen.blit(me.image1, me.rect)
                else:
                    screen.blit(me.image2, me.rect)
            else:  # 死亡
                me_down_sound.play()  # 死亡音效
                if not (delay % 3):  # 3的倍数
                    screen.blit(each.destroy_images[me_destroy_index], each.rect)
                    me_destroy_index = (me_destroy_index + 1) % 4
                    # 剩余生命数量
                    if me_destroy_index == 0:  #
                        life_num -= 1  # 生命减一
                        me.reset()  # 重新初始化飞机
                        pygame.time.set_timer(INVINCEBLE_TIME, 3 * 1000)  # 无敌时间3s

            # 绘制剩余炸弹数量
            bomb_text = bomb_font.render("x %d" % bomb_num, True, WHITE)
            text_rect = bomb_text.get_rect()
            screen.blit(bomb_image, (10, height - 10 - bomb_rect.height))  # 左下角
            screen.blit(bomb_text, (20 + bomb_rect.width, height - 5 - text_rect.height))

            if life_num:  # 还有命
                for i in range(life_num):
                    screen.blit(life_image, \
                                (width - 10 - (i + 1) * life_rect.width, \
                                 height - 10 - life_rect.height))  # 右下角

            score_text = score_font.render(str("Score: %s" % score), True, WHITE)  # 分数
            screen.blit(score_text, (10, 5))
        elif life_num == 0:  # 没命了
            pygame.mixer.music.stop()
            pygame.mixer.stop()

            # 停止发放补给
            pygame.time.set_timer(SUPPLY_TIME, 0)

            if not recorded:  # 没有记录
                recorded = True
                # sql = 'select * from user where username = "'+name+'" '
                cursor = db.cursor()
                sql = "select * from record_score where username = %s"
                # sql = "select * from user "
                # 使用游标对象执行SQL语句；
                cursor.execute(sql, name)
                # 多条数据
                data = cursor.fetchall()
                print(data)
                sql1 = "update record_score set score = %s where username = %s;"
                sql2 = "insert into record_score(username,score) values(%s,%s);"
                list1 = [
                    (name, str(score))
                ]
                if data:  # 存在该玩家的历史记录 则更新
                    cursor.execute(sql1, (str(score), name))
                    db.commit()
                else:  # 否则插入该数据
                    try:
                        # 使用游标对象执行SQL语句；
                        cursor.executemany(sql2, list1)
                        db.commit()
                    except Exception as ex:
                        print('插入语句错误' + str(ex))
                        db.rollback()
                    finally:
                        db.close()

                # 断开数据库的连接，释放资源；
                # db.close()
                # 读取历史最高分
                #################################################
                #################################################
                with open("record.txt", "r") as f:  # 读取文件
                    record_score = int(f.read())
                with open("recordname.txt", "r") as f:  # 读取文件
                    record_name = str(f.read())
                if score > record_score:  # 当分数大于记录里面的分数
                    with open("record.txt", "w") as f:  # 写入最近一次最高的分数
                        f.write(str(score))
                    with open("records.txt", "r") as f:  # 写入排行榜最近一次最高分的昵称
                        record_bestname = str(f.read())
                    with open("recordname.txt", "w") as f:  # 写入昵称
                        f.write(str(record_bestname))
            # 绘制结束画面
            record_score_text = score_font.render("Best: %d User_Name:%s" % (record_score, record_name), True, WHITE)
            screen.blit(record_score_text, (50, 50))

            gameover_text1 = gameover_font.render("Your Score: ", True, WHITE)
            gameover_text1_rect = gameover_text1.get_rect()
            gameover_text1_rect.left, gameover_text1_rect.top = \
                (width - gameover_text1_rect.width) // 2, height // 2
            screen.blit(gameover_text1, gameover_text1_rect)

            gameover_text2 = gameover_font.render(str(score), True, WHITE)
            gameover_text2_rect = gameover_text2.get_rect()
            gameover_text2_rect.left, gameover_text2_rect.top = \
                (width - gameover_text2_rect.width) // 2, \
                gameover_text1_rect.bottom + 10
            screen.blit(gameover_text2, gameover_text2_rect)

            again_rect.left, again_rect.top = \
                (width - again_rect.width) // 2, \
                gameover_text2_rect.bottom + 50
            screen.blit(again_image, again_rect)

            gameover_rect.left, gameover_rect.top = \
                (width - again_rect.width) // 2, \
                again_rect.bottom + 10
            screen.blit(gameover_image, gameover_rect)

            # 检测用户的鼠标操作
            # 如果用户按下鼠标左键
            if pygame.mouse.get_pressed()[0]:
                pos = pygame.mouse.get_pos()  # 鼠标停留位置
                if again_rect.left < pos[0] < again_rect.right and \
                        again_rect.top < pos[1] < again_rect.bottom:
                    main(name)  # 重新开始
                elif gameover_rect.left < pos[0] < gameover_rect.right and \
                        gameover_rect.top < pos[1] < gameover_rect.bottom:
                    pygame.quit()  # 退出游戏
                    sys.exit()

        screen.blit(paused_image, paused_rect)

        # 切换图片
        if not (delay % 5):
            switch_image = not switch_image

        delay -= 1
        if not delay:
            delay = 100

        pygame.display.flip()  # 刷新
        clock.tick(60)  # 60帧


######################
window = tk.Tk()  # 调用Tk()创建主窗口
window.title('欢迎来到飞机大战简易版v1.0')  # 设置登录窗口标题
window.geometry('450x300')  # 设置窗口大小:宽x高,注,此处不能为 "*",必须使用 "x"
# 创建一个200X500的画布
canvas = tk.Canvas(window, height=300, width=500)
# 登录界面的背景图片路径
image_file = tk.PhotoImage(file='images/window.png')

# 更改左上角窗口的的icon图标,加载pygamelogo标
# root_window.iconbitmap('C:/Users/Administrator/Desktop/favicon.ico')
# image = tk.Image.open("images/hut.jpg")
# image_file = ImageTk.PhotoImage(image)
# image_file = tk.PhotoImage(file="images/hut.png")
# 什么位置插入登录界面背景图片
image = canvas.create_image(0, 0, anchor='nw', image=image_file)
canvas.pack(side='top')
tk.Label(window, text='用户名:').place(x=100, y=150)  # 放到window登录窗口的指定坐标上
tk.Label(window, text='密码:').place(x=100, y=190)  # 放到window登录窗口的指定坐标上
# 用户名输入框
var_usr_name = tk.StringVar()
entry_usr_name = tk.Entry(window, textvariable=var_usr_name)  # 放到window登录窗口
entry_usr_name.place(x=160, y=150)  # 指定坐标
# 密码输入框
var_usr_pwd = tk.StringVar()
entry_usr_pwd = tk.Entry(window, textvariable=var_usr_pwd, show='*')  # 隐藏密码输入符号 放到window登录窗口
entry_usr_pwd.place(x=160, y=190)  # 指定坐标


# 登录函数
def usr_log_in():
    # 输入框获取用户名密码
    usr_name = var_usr_name.get()  # 获取用户输入的用户名
    usr_pwd = var_usr_pwd.get()  # 获取用户输入的密码
    # 从本地字典获取用户信息，如果没有则新建本地数据库
    try:
        with open('usr_info.pickle', 'rb') as usr_file:
            usrs_info = pickle.load(usr_file)
    except FileNotFoundError:
        with open('usr_info.pickle', 'wb') as usr_file:
            usrs_info = {'admin': 'admin'}
            pickle.dump(usrs_info, usr_file)  # 序列化user.info写入user_file
    # 判断用户名和密码是否匹配

    # mysql数据库存入模块
    sql = "select * from user where username = %s"
    # 开启mysql的游标功能，创建一个游标对象；
    cursor = db.cursor()
    # 使用游标对象执行SQL语句；
    cursor.execute(sql, usr_name)
    # db.commit()
    data = cursor.fetchall()

    if usr_name in usrs_info and data:
        if usr_pwd == usrs_info[usr_name] and __name__ == "__main__":
            tk.messagebox.showinfo(title='welcome',
                                   message='欢迎您：' + usr_name)
            # with open("records.txt", "a+") as f:
            with open("records.txt", "w+") as f:
                f.write(str(usr_name))  # 每次都只写最近一次登入的用户名 -> 可以修改成追加形式 加上数据库来存储玩家信息 更新成为排行榜
                # f.write(str(usr_name)+"\n")
            window.destroy()
            try:
                Menu(str(usr_name))  # 进入菜单
            except SystemExit:
                pass
            except:
                traceback.print_exc()
                pygame.quit()
                input()
            window.destroy()
        else:
            tk.messagebox.showerror(message='密码错误')
    # 用户名密码不能为空
    elif usr_name == '' or usr_pwd == '':
        tk.messagebox.showerror(message='用户名或密码为空')
    # 不在数据库中弹出是否注册的框
    else:
        is_signup = tk.messagebox.askyesno('欢迎', '您还没有注册，是否现在注册')
        if is_signup:
            usr_sign_up()


# 注册函数
def usr_sign_up():
    # 确认注册时的相应函数
    def signtowcg():
        # 获取输入框内的内容
        nn = new_name.get()
        np = new_pwd.get()
        npf = new_pwd_confirm.get()  # 获取第二次输入密码的字符串

        # # mysql数据库存入模块
        # sql = "select * from user where username = %s"
        # # 开启mysql的游标功能，创建一个游标对象；
        # cursor = db.cursor()
        # # 使用游标对象执行SQL语句；
        # cursor.execute(sql, nn)
        # data = cursor.fetchall()
        # if data:
        #     print(data)
        # sql = "insert into user(username,password) values(nn,np)"

        # 本地加载已有用户信息,如果没有则已有用户信息为空
        try:
            with open('usr_info.pickle', 'rb') as usr_file:
                exist_usr_info = pickle.load(usr_file)
        except FileNotFoundError:
            exist_usr_info = {}

        # mysql数据库存入模块
        sql = "select * from user where username = %s"
        # 开启mysql的游标功能，创建一个游标对象；
        cursor = db.cursor()
        # 使用游标对象执行SQL语句；
        cursor.execute(sql, nn)
        # db.commit()
        data = cursor.fetchall()

        # 检查用户名存在、密码为空、密码前后不一致
        if nn in exist_usr_info and data:
            tk.messagebox.showerror('错误', '用户名已存在')
            db.close()
        elif np == '' or nn == '':
            tk.messagebox.showerror('错误', '用户名或密码为空')
            db.close()
        elif np != npf:
            tk.messagebox.showerror('错误', '密码前后不一致')
            db.close()
        # 注册信息没有问题则将用户名密码写入数据库
        else:
            exist_usr_info[nn] = np
            with open('usr_info.pickle', 'wb') as usr_file:
                pickle.dump(exist_usr_info, usr_file)
            tk.messagebox.showinfo('欢迎', '注册成功')
            list1 = [
                (nn, np)
            ]
            # mysql数据库存入模块
            sql = "insert into user(username,password) values(%s,%s)"
            # 开启mysql的游标功能，创建一个游标对象；
            cursor = db.cursor()
            # 使用游标对象执行SQL语句；
            cursor.executemany(sql, list1)
            db.commit()
            db.close()
            # data = cursor.fetchall()
            # if data:
            #     print(data)

            # 注册成功关闭注册框
            window_sign_up.destroy()

    # 新建注册界面
    window_sign_up = tk.Toplevel(window)
    window_sign_up.geometry('350x200')
    window_sign_up.title('注册')
    # 用户名变量及标签、输入框
    new_name = tk.StringVar()
    tk.Label(window_sign_up, text='用户名：').place(x=10, y=10)
    tk.Entry(window_sign_up, textvariable=new_name).place(x=150, y=10)
    # 密码变量及标签、输入框
    new_pwd = tk.StringVar()
    tk.Label(window_sign_up, text='请输入密码：').place(x=10, y=50)
    tk.Entry(window_sign_up, textvariable=new_pwd, show='*').place(x=150, y=50)
    # 重复密码变量及标签、输入框
    new_pwd_confirm = tk.StringVar()
    tk.Label(window_sign_up, text='请再次输入密码：').place(x=10, y=90)
    tk.Entry(window_sign_up, textvariable=new_pwd_confirm, show='*').place(x=150, y=90)
    # 确认注册按钮及位置
    bt_confirm_sign_up = tk.Button(window_sign_up, text='确认注册',
                                   command=signtowcg)
    bt_confirm_sign_up.place(x=150, y=130)


# 退出的函数
def usr_sign_quit():
    window.destroy()  # 回收窗口


# 登录 注册按钮
bt_login = tk.Button(window, text='登录', command=usr_log_in)  # 放到window登录窗口
bt_login.place(x=140, y=230)  # 指定坐标
bt_logup = tk.Button(window, text='注册', command=usr_sign_up)  # 放到window登录窗口
bt_logup.place(x=210, y=230)  # 指定坐标
bt_logquit = tk.Button(window, text='退出', command=usr_sign_quit)  # 放到window登录窗口
bt_logquit.place(x=280, y=230)  # 指定坐标
# 主循环
window.mainloop()  # 开启主循环，让窗口处于显示状态
################
